import typer
import sys


sys.path.append("../")  # noqa
from config import aredis
from core.es import  Index_KJJ_ACTIVITY_REGISTER, Index_KJJ_DEPARTMENT

from api.search.import_activity import import_activity_members
from api.search.import_department import import_department
from api.search.schema_act_member import Base
from config import col_alumni
from api.search.import_alumni import import_alumni
from api.search.schema_alumni import Member
from api.search.schema_institution import Department

from bson import ObjectId

app = typer.Typer()


@app.command()
def create_alumni_index():
    def setup():
        """Create an IndexTemplate and save it into elasticsearch."""
        index_template = Member._index.as_template("base")
        index_template.save()

    setup()
    Member.init()


@app.command()
def create_department_index():
    def setup():
        """Create an IndexTemplate and save it into elasticsearch."""
        index_template = Department._index.as_template("base")
        index_template.save()

    setup()
    Department.init()


@app.command()
def bulk_department():
    import_department()


@app.command()
def bulk_alumni(start: int = typer.Option(0, help="start index"), end: int = typer.Option(-1, help="end index")):
    _total = end
    if end == -1:
        _total = col_alumni.count_documents({"is_deleted": {"$ne": True}})
    size = 3
    for offset in range(start, _total, size):
        import_alumni(offset, size)


@app.command()
def create_activity_index():
    def setup():
        """Create an IndexTemplate and save it into elasticsearch."""
        index_template = Base._index.as_template("base")
        index_template.save()

    setup()
    Base.init()


@app.command()
def bulk_activity():
    import_activity_members()


@app.command()
def delete_alumni():
    Member._index.delete()
    create_alumni_index()


@app.command()
def delete_act():
    from elasticsearch_dsl import Index
    index = Index(Index_KJJ_ACTIVITY_REGISTER)
    index.delete(ignore=[400, 404])
    create_activity_index()


@app.command()
def delete_inst():
    from elasticsearch_dsl import Index
    index = Index(Index_KJJ_DEPARTMENT)
    index.delete(ignore=[400, 404])
    create_department_index()


if __name__ == '__main__':
    app()


